package com.mh.mh.netty.reconnheart;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Administrator
 */
@ChannelHandler.Sharable// 线程安全
public class HandlerClientReconnHeart extends SimpleChannelInboundHandler<ByteBuf> {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连上服务器了");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        /***
         * 处理接收到的消息
         */
        System.out.println("接收到的消息:"+byteBuf.toString(CharsetUtil.UTF_8));
    }

    // 记得捕获异常，把连接断开
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        /**
         * 处理IO异常
         */
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        // 超时检测
        if(evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent) evt;
            if(event.state() == IdleState.READER_IDLE){// 这里判断，是读超时，还是写超时

                System.out.println("客户端读取消息包超时");

                // 检测到读超时，就向服务器端发送一个消息包
                SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss SSS");
                String strDate = df.format(new Date());
                ctx.writeAndFlush(Unpooled.copiedBuffer("我是心跳消息 "+strDate + "\r\n", CharsetUtil.UTF_8));

            }
        }

    }
}
